package service;

import data.*;

/**
 * 坦克控制服务类
 */
public class TankService {
    // -------------------- service --------------------
    private CollisionService collisionService;

    public TankService() {
        this.collisionService = new CollisionService();
    }

    /**
     * 功能: 坦克移动控制
     * 参数:
     *   tank: 坦克数据
     *   direction: 移动方向
     * 返回值: void
     */
    public void moveTank(TankData tank, int direction) {
        if (tank.getState() != 1) return;

        if (tank.getDirection() == direction) {
            // 相同方向，尝试移动
            if (!collisionService.checkTankMoveCollision(tank, direction)) {
                switch (direction) {
                    case 0: tank.setY(tank.getY() - tank.getSpeed()); break; // 上
                    case 1: tank.setX(tank.getX() + tank.getSpeed()); break; // 右
                    case 2: tank.setY(tank.getY() + tank.getSpeed()); break; // 下
                    case 3: tank.setX(tank.getX() - tank.getSpeed()); break; // 左
                }
            }
        } else {
            // 不同方向，只改变方向
            tank.setDirection(direction);
        }
    }

    /**
     * 功能: 坦克射击控制
     * 参数:
     *   tank: 坦克数据
     * 返回值: void
     */
    public void tankShoot(TankData tank) {
        if (tank.getState() != 1) return;

        long currentTime = System.currentTimeMillis();
        if (currentTime - tank.getLastShootTime() < 300) { // 射击间隔300ms
            return;
        }

        // 寻找空闲子弹
        for (BulletData bullet : tank.getBulletPool()) {
            if (bullet.getState() == 0) {
                // 计算子弹初始位置
                int bulletX = tank.getX() + 16; // 坦克中心
                int bulletY = tank.getY() + 16;

                switch (tank.getDirection()) {
                    case 0: bulletY = tank.getY() - 8; break; // 上
                    case 1: bulletX = tank.getX() + 40; break; // 右
                    case 2: bulletY = tank.getY() + 40; break; // 下
                    case 3: bulletX = tank.getX() - 8; break; // 左
                }

                bullet.setX(bulletX);
                bullet.setY(bulletY);
                bullet.setDirection(tank.getDirection());
                bullet.setState(1);

                tank.setLastShootTime(currentTime);
                break;
            }
        }
    }
    // -------------------- service --------------------
}